package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.market.entity.InfoDeliveryAddress;
import com.fjec.market.mapper.InfoDeliveryAddressMapper;
import com.fjec.market.service.IInfoDeliveryAddressService;
import com.fjec.market.view.DeliveryAddressVO;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 009.商户收货地址表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-14
 */
@Service
@Transactional
public class InfoDeliveryAddressServiceImpl extends ServiceImpl<InfoDeliveryAddressMapper, InfoDeliveryAddress> implements IInfoDeliveryAddressService {

    @Resource
    private InfoDeliveryAddressMapper mapper;

    @Resource
    private SequenceIdGenerator idGenerator;

    @Override
    public JsonResult saveDeliveryAddress(Long userId, Integer busiType, String phone,
                                          String contact, String prov, String city, String district,
                                          String address1, String address2, Integer defAddr) {
        InfoDeliveryAddress entity = InfoDeliveryAddress.builder()
                .id(idGenerator.nextId())
                .userId(userId)
                .busiType(busiType)
                .phone(phone)
                .contact(contact)
                .prov(prov)
                .city(city)
                .district(district)
                .address1(address1)
                .address2(address2)
                .defAddr(defAddr)
                .delFlag(0)
                .createTime(DateUtil.nowLdt())
                .build();
        // 是否为第一个录入的地址，如果是则设置为默认地址
        QueryWrapper<InfoDeliveryAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserId", userId)
//                .eq("BusiType", busiType)
                .eq("DelFlag", 0);
        Integer count = mapper.selectCount(queryWrapper);
        if (count == null || count == 0) {
            entity.setDefAddr(1);
        }
        mapper.insert(entity);
        return JsonResult.success()
                .code(EnumSysCode.MSG_6002.getCode())
                .message(EnumSysCode.MSG_6002.getMsg())
                .build();
    }

    @Override
    public JsonResult deleteDeliveryAddress(Long id) {
        InfoDeliveryAddress entity = mapper.selectById(id);
        if (entity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0008.getCode())
                    .message(EnumSysCode.ERR_0008.getMsg())
                    .build();
        }
        entity.setDelFlag(1);
        entity.setUpdateTime(DateUtil.nowLdt());
        mapper.updateById(entity);
        return JsonResult.success()
                .code(EnumSysCode.MSG_6003.getCode())
                .message(EnumSysCode.MSG_6003.getMsg())
                .build();
    }

    @Override
    public JsonResult updateDeliveryAddress(Long id, String phone, String contact, String prov,
                                            String city, String district, String address1, String address2) {
        InfoDeliveryAddress entity = mapper.selectById(id);
        if (entity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0008.getCode())
                    .message(EnumSysCode.ERR_0008.getMsg())
                    .build();
        }
        InfoDeliveryAddress updateEntity = InfoDeliveryAddress.builder()
                .phone(phone)
                .contact(contact)
                .prov(prov)
                .city(city)
                .district(district)
                .address1(address1)
                .address2(address2)
                .updateTime(DateUtil.nowLdt())
                .build();
        UpdateWrapper<InfoDeliveryAddress> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        mapper.update(updateEntity, wrapper);
        return JsonResult.success()
                .code(EnumSysCode.MSG_6003.getCode())
                .message(EnumSysCode.MSG_6003.getMsg())
                .build();
    }

    @Override
    public JsonResult setDefaultDeliveryAddress(Long id) {
        // 查询实体
        InfoDeliveryAddress entity = mapper.selectById(id);
        // 更新所有相关defAddr为0
        UpdateWrapper<InfoDeliveryAddress> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("UserId", entity.getUserId())
//                .eq("BusiType", entity.getBusiType())
                .eq("DelFlag", 0);
        InfoDeliveryAddress updateEntity = InfoDeliveryAddress.builder()
                .defAddr(0)
                .updateTime(DateUtil.nowLdt())
                .build();
        mapper.update(updateEntity, updateWrapper);
        // 更新本条数据为默认
        entity.setDefAddr(1);
        entity.setUpdateTime(DateUtil.nowLdt());
        mapper.updateById(entity);
        return JsonResult.success()
                .code(EnumSysCode.MSG_6003.getCode())
                .message(EnumSysCode.MSG_6003.getMsg())
                .build();
    }

    @Override
    public JsonResult getDefaultDeliveryAddress() throws Exception {
        Long userId = AccountInfo.getUserId();
        QueryWrapper<InfoDeliveryAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId)
                .eq("defAddr", 1)
                .eq("delFlag", 0)
                .orderByDesc("defAddr");
        List<InfoDeliveryAddress> entityList = mapper.selectList(wrapper);
        if (entityList != null && !entityList.isEmpty()) {
            DeliveryAddressVO view = new DeliveryAddressVO();
            BeanUtils.copyProperties(view, entityList.get(0));
            return JsonResult.success()
                    .data(view)
                    .build();
        } else {
            return JsonResult.success()
                    .data(null)
                    .build();
        }
    }

    @Override
    public JsonResult getDeliveryAddressList(Long userId, Integer busiType) throws Exception {
        QueryWrapper<InfoDeliveryAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("userId", userId);
//        wrapper.eq("busiType", busiType);
        List<InfoDeliveryAddress> entityList = mapper.selectList(wrapper);
        List<DeliveryAddressVO> resultList = new ArrayList<>();
        for (InfoDeliveryAddress entity : entityList) {
            DeliveryAddressVO view = new DeliveryAddressVO();
            BeanUtils.copyProperties(view, entity);
            resultList.add(view);
        }
        return JsonResult.success()
                .data(resultList)
                .build();
    }

    @Override
    public JsonResult getDeliveryAddress(Long id) throws Exception {
        InfoDeliveryAddress entity = mapper.selectById(id);
        DeliveryAddressVO view = new DeliveryAddressVO();
        BeanUtils.copyProperties(view, entity);
        return JsonResult.success()
                .data(view)
                .build();
    }
}
